package com.ruoyi.common.utils.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;

/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtils extends FileUtil
{
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";


	//把一个文件中的内容读取成一个String字符串
	public static String getStr(File jsonFile){
		String jsonStr = "";
		try {
			FileReader fileReader = new FileReader(jsonFile);
			Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			fileReader.close();
			reader.close();
			jsonStr = sb.toString();
			return jsonStr;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

    public static void downloadFile(String downloadUrl,String saveFileName){
    	try{
			System.out.println("downloadUrl: " + downloadUrl);
			System.out.println("saveFileName: " + saveFileName);
//			String dialAudioUrl = "http://172.16.20.220:80/20210506/f2a2c3be01194a63953d4b42d2588465.wav";
//			String saveFile = "/data/upload/audio/f2a2c3be01194a63953d4b42d2588465.wav";
			URL url = new URL("https://cdn.assets.scratch.mit.edu/internalapi/asset/a5865738283613a2725b2c9dda6d8c78.svg/get");
			ReadableByteChannel rbc = Channels.newChannel(url.openStream());
			FileOutputStream fos = new FileOutputStream(saveFileName);
			fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
			fos.close();
			rbc.close();
		}catch (Exception e){
    		e.printStackTrace();
		}
	}



	public static void downloadFile1(String downloadUrl,String path,String saveFileName){

		System.out.println("downloadUrl: " + downloadUrl);
		System.out.println("saveFileName: " + saveFileName);
		try {
			//自动创建文件夹
			File file = new File(path);
			if (!file.exists() && !file.isDirectory()) {
				System.out.println("新建目录");
				file.mkdirs();
			}
			//解析下载地址
			URL url = new URL(downloadUrl);
			URLConnection cnt = url.openConnection();
			InputStream inStream = cnt.getInputStream();
			System.out.println("开始下载:保存路径： " + path + saveFileName);

			FileOutputStream fos = new FileOutputStream(path + saveFileName);
			int bytesum = 0;
			int byteread;
			byte[] buffer = new byte[1204];
			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread;
				fos.write(buffer, 0, byteread);
			}
			System.out.println("下载完成");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}







    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename)
    {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 检查文件是否可下载
     *
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    public static boolean checkAllowDownload(String resource)
    {
        // 禁止目录上跳级别
        if (StrUtil.contains(resource, ".."))
        {
            return false;
        }

        // 检查允许下载的文件规则
        if (ArrayUtil.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
        {
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

    /**
     * 下载文件名重新编码
     *
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
        }
        return filename;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response 响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException
    {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }
}
